package com.ruoyi.web.controller.vantController.orderController;


import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.ruoyi.common.utils.TimeUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.zhuangxiumain.orderformMain.OrderMaster;
import com.ruoyi.system.domain.zhuangxiumain.vo.OrderVo;
import com.ruoyi.system.service.vantservice.wxpayservice.WxAppPayService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@CrossOrigin
@RestController
@RequestMapping("/api/wxPay")
public class ApiWxPayController {

    @Autowired
    private WxAppPayService wxService;

    @Autowired
    private HttpServletRequest request;

    /**
     * APP支付
     *
     * @param price
     * @return
     * @throws Exception
     */
    @GetMapping("/wxpay/{price}")
    public Map wxAdd(@PathVariable(value = "price", required = false) int price) throws Exception {
        System.out.println("price:" + price);
        return wxService.doUnifiedOrder(request, price);
    }

    /**
     * 微信支付回调
     *
     * @param request
     * @return
     */
    @PostMapping("/wxnotify")
    @ApiOperation("微信回调")
    public String wxPayNotify(HttpServletRequest request) {
        String resXml = "";
        try {
            InputStream inputStream = request.getInputStream();
            //将InputStream转换成xmlString
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            resXml = sb.toString();
            String result = wxService.payBack(resXml);
            return result;
        } catch (Exception e) {
            System.out.println("微信手机支付失败:" + e.getMessage());
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return result;
        }
    }

    /**
     * @return Map
     * @Description H5调起微信支付微信浏览器外支付
     */
    @PostMapping(value = "/orders_other")
    public Map<String, String> orders_other(@RequestBody OrderMaster orderMaster) {
        try {
            System.out.println("orderMaster:"+orderMaster.getPaymentMoney());
            //拼接下单地址参数
            Map<String, String> paraMap = new HashMap<String, String>();
//            //获取请求ip地址
//            String ip = getIP(request);
            String spbill_create_ip = getIpAddr(request);// IP地址
            paraMap.put("appid", "wx05c8af6ffe91bc2b");
            paraMap.put("mch_id", "1605920289");
            paraMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paraMap.put("body", "陶小建自助平台");
            int randomNum  = (int) (Math.random() * 1999+5000);
            paraMap.put("out_trade_no", TimeUtils.getSysTime("yyyyMMddHHmmss")+randomNum);//商品的订单号每次要唯一
            paraMap.put("total_fee", "1");
            paraMap.put("spbill_create_ip", spbill_create_ip);
            paraMap.put("notify_url", "http://51jhf.com:8080/api/wxPay/notify");// 此路径是微信服务器调用支付结果通知路径
            paraMap.put("trade_type", "MWEB");
            paraMap.put("scene_info", "{\"h5_info\":{\"type\":\"Wap\",\"wap_url\":'随意地址可以是公司官网地址',\"wap_name\": \"订单支付\"}}");

            String sign = WXPayUtil.generateSignature(paraMap, "zhuangxiuapp123456789qwertyuiopa");
            paraMap.put("sign", sign);
            String xml = WXPayUtil.mapToXml(paraMap);//将所有参数(map)转xml格式

            // 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
            String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

            String xmlStr = HttpUtils.sendPost(unifiedorder_url, xml);//发送post请求"统一下单接口"

            //以下内容是返回前端页面的json数据
            String mweb_url = "";//跳转链接
            if (xmlStr.indexOf("SUCCESS") != -1) {
                Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
                mweb_url = (String) map.get("mweb_url");

//                //支付完返回浏览器跳转的地址，如跳到查看订单页面
//                String redirect_url = "http://51jhf.com/txj";
//                String redirect_urlEncode = URLEncoder.encode(redirect_url, "utf-8");//对上面地址urlencode
//                mweb_url = mweb_url + "&redirect_url=" + redirect_urlEncode;//拼接返回地址
            }

            Map<String, String> payMap = new HashMap<String, String>();
            payMap.put("mweb_url", mweb_url);
            return payMap;
        } catch (Exception e) {
//            _log.info("微信支付异常");
            System.out.println("微信支付异常");
        }
        return null;
    }



    @RequestMapping(value = "/notify")
    public void weixinPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader reader = request.getReader();
        String line = "";
        Map map = new HashMap();
        String xml = "<xml><return_code><![CDATA[FAIL]]></xml>";;
        JSONObject dataInfo = new JSONObject();
        StringBuffer inputString = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            inputString.append(line);
        }
        request.getReader().close();
        System.out.println("----接收到的报文---"+inputString.toString());
        if(inputString.toString().length()>0){
            map = WXPayUtil.xmlToMap(inputString.toString());
        }else{
            System.out.println("接受微信报文为空");
        }
        System.out.println("map="+map);
        if(map!=null && "SUCCESS".equals(map.get("result_code"))){
            //成功的业务。。。
            xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        }else{
            //失败的业务。。。
        }
        //告诉微信端已经确认支付成功
        response.getWriter().write(xml);
    }


    /**
     * 获取用户实际ip
     * @param request
     * @return
     */
    public String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }


    public static void main(String[] args){
        try {
            //拼接下单地址参数
            Map<String, String> paraMap = new HashMap<String, String>();
//            //获取请求ip地址
//            String ip = getIP(request);

            paraMap.put("appid", "wx05c8af6ffe91bc2b");
            paraMap.put("mch_id", "1605920289");
            paraMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paraMap.put("body", "XX商城-订单结算");
            paraMap.put("out_trade_no", "201810102936543");//商品的订单号每次要唯一
            paraMap.put("total_fee", "1");
            paraMap.put("spbill_create_ip", "127.0.0.1");
            paraMap.put("notify_url", "http://51jhf.com/pay/wxPay/notify");// 此路径是微信服务器调用支付结果通知路径
            paraMap.put("trade_type", "MWEB");
            paraMap.put("scene_info", "{\"h5_info\":{\"type\":\"Wap\",\"wap_url\":'随意地址可以是公司官网地址',\"wap_name\": \"订单支付\"}}");

            String sign = WXPayUtil.generateSignature(paraMap, "zhuangxiuapp123456789qwertyuiopa");
            paraMap.put("sign", sign);
            String xml = WXPayUtil.mapToXml(paraMap);//将所有参数(map)转xml格式

            // 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
            String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

            String xmlStr = HttpUtils.sendPost(unifiedorder_url, xml);//发送post请求"统一下单接口"

            //以下内容是返回前端页面的json数据
            String mweb_url = "";//跳转链接
            if (xmlStr.indexOf("SUCCESS") != -1) {
                Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
                mweb_url = (String) map.get("mweb_url");

                //支付完返回浏览器跳转的地址，如跳到查看订单页面
                String redirect_url = "http://51jhf.com/orders";
                String redirect_urlEncode = URLEncoder.encode(redirect_url, "utf-8");//对上面地址urlencode
                mweb_url = mweb_url + "&redirect_url=" + redirect_urlEncode;//拼接返回地址
            }

            Map<String, String> payMap = new HashMap<String, String>();
            payMap.put("mweb_url", mweb_url);
            System.out.println(payMap);
        } catch (Exception e) {
//            _log.info("微信支付异常");
            System.out.println("微信支付异常");
        }
    }
}
